package com.hisense.ovcloud.apicontrol.client;

import cn.hutool.json.JSONUtil;
import com.hisense.ovcloud.apicontrol.dto.req.VerifyReq;
import com.hisense.ovcloud.apicontrol.dto.resp.ACBaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Component
@Slf4j
public class JulinkPsClient {

    private final WebClient webClient;

    @Value("${ps.url:ac-new-ps:9096}")
    private String psUrl;

    @Value("${http.timeout.seconds:5}")
    private Long TIME_OUT;

    @Value("${http.retry.times:2}")
    private Long RETRY_TIMES;

    public JulinkPsClient(@Qualifier("base") WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<ACBaseResponse> verify(VerifyReq req) {
        return webClient.post()
                .uri("http://" + psUrl + "/ac-julink-ps/verify")
                .body(Mono.just(req), VerifyReq.class)
                .retrieve()
                .bodyToMono(ACBaseResponse.class)
                .retry(RETRY_TIMES)
                .doOnSuccess(res -> log.info("verify token {} success! res: {}", req.getToken(), JSONUtil.toJsonStr(res)))
                .doOnError(err -> log.error("verify token {} failed! res: {}", req.getToken(), err.getMessage()))
                .timeout(Duration.ofSeconds(TIME_OUT));
    }
}

